<template>
  <div class="maintenance-request-container">
    <el-card>
      <div slot="header" class="card-header">
        <span>维修申请管理</span>
      </div>
      <div class="search-container">
       <el-input v-model.trim="searchForm.requestCode" placeholder="申请编号" style="width: 200px; margin-right: 10px;"></el-input>
        <el-select v-model="searchForm.status" placeholder="申请状态" style="width: 150px; margin-right: 10px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="待指派" value="1"></el-option>
          <el-option label="维修中" value="2"></el-option>
          <el-option label="已完成" value="3"></el-option>
          <el-option label="已关闭" value="4"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        <el-button type="success" @click="handleAdd">新增申请</el-button>
      </div>
      
      <el-table :data="requestList" style="width: 100%;">
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="requestCode" label="申请编号" width="120"></el-table-column>
          <el-table-column label="设备名称">
            <template slot-scope="scope">
              {{ getDeviceName(scope.row.deviceId || scope.row.device_id) }}
            </template>
          </el-table-column>
          <el-table-column prop="faultDescription" label="故障描述" show-overflow-tooltip></el-table-column>
          <el-table-column prop="priority" label="优先级">
            <template slot-scope="scope">
              <el-tag size="small" v-if="scope.row.priority === 1" type="danger">紧急</el-tag>
              <el-tag size="small" v-else-if="scope.row.priority === 2" type="warning">普通</el-tag>
              <el-tag size="small" v-else-if="scope.row.priority === 3" type="success">低</el-tag>
              <el-tag size="small" v-else type="info">未知</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="申请人">
            <template slot-scope="scope">
              {{ userMap[scope.row.requestUserId] || '未知用户' }}
            </template>
          </el-table-column>
          <el-table-column label="申请时间">
            <template slot-scope="scope">
              {{ formatDate(scope.row.requestTime) }}
            </template>
          </el-table-column>
          <el-table-column label="预估费用">
            <template slot-scope="scope">
              {{ scope.row.estimatedCost || 0 }} 元
            </template>
          </el-table-column>

          <el-table-column prop="repairRemarks" label="维修备注" show-overflow-tooltip></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="statusMap[scope.row.status]">{{ statusText[scope.row.status] || '未知状态' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="small" type="primary" @click="handleView(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :total="total"
          :page-size="page_size"
          :current-page="page_num"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑申请对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="设备名称" prop="device_id">
          <el-select v-model="form.device_id" placeholder="请选择设备">
              <el-option v-for="device in deviceList" :key="device.id" :label="device.device_name" :value="device.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="故障描述" prop="fault_description">
					<el-input v-model.trim="form.fault_description" type="textarea" placeholder="请详细描述故障情况" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model.number="form.priority" placeholder="请选择优先级">
            <el-option label="紧急" :value="1"></el-option>
            <el-option label="普通" :value="2"></el-option>
            <el-option label="低" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预计费用" prop="estimated_cost">
          <el-input v-model.number="form.estimated_cost" placeholder="请输入预计费用（可选）" suffix-icon="el-icon-money">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="维修备注" prop="repair_remarks">
          <el-input v-model.trim="form.repair_remarks" type="textarea" placeholder="请输入维修备注（可选）" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交申请</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import repairApi from '@/api/repair-request'
import deviceApi from '@/api/device'
import userApi from '@/api/sys-user'

export default {
  name: 'RepairRequest',
  data() {
      return {
        searchForm: {
          requestCode: '',
          status: '',
          request_time: ''
        },
        requestList: [],
        total: 0,
        page_num: 1,
        page_size: 10,
        dialogVisible: false,
        dialogTitle: '新增维修申请',
        form: {
          id: '',
          device_id: '',
          fault_description: '',
          priority: 2, // 默认普通优先级
          estimated_cost: '',
          repair_remarks: ''
        },
        deviceList: [],
        userMap: {},  // 缓存用户信息
        rules: {
          device_id: [{ required: true, message: '请选择设备', trigger: 'change' }],
          fault_description: [{ required: true, message: '请描述故障情况', trigger: 'blur' }],
          priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
          estimated_cost: [{ type: 'number', min: 0, message: '预计费用必须大于等于0', trigger: 'blur' }]
        },
        statusMap: {
          '1': 'warning',
          '2': 'info',
          '3': 'success',
          '4': 'danger'
        },
        statusText: {
          '1': '待指派',
          '2': '维修中',
          '3': '已完成',
          '4': '已关闭'
        },
        // 优先级映射
        priorityMap: {
          '1': 'danger',
          '2': 'warning',
          '3': 'success'
        },
        priorityText: {
          '1': '紧急',
          '2': '普通',
          '3': '低'
        }
      }
  },
  created() {
    this.getRequestList()
    this.getDeviceList()
  },
  methods: {
    // 获取申请列表
    getRequestList() {
        // 调用API获取维修申请列表
        const params = {
          page_num: this.page_num,
          page_size: this.page_size,
          ...this.searchForm
        }
        repairApi.list(params)
          .then(res => {
            if (res && res.data) {
              this.requestList = res.data.records || []
              this.total = res.data.total || 0
              // 为每条记录获取用户名称
              this.requestList.forEach(item => {
                this.getUserName(item.requestUserId)
                if (item.repairUserId) {
                  this.getUserName(item.repairUserId)
                }
              })
            } else {
              this.requestList = []
              this.total = 0
            }
          })
          .catch(error => {
            this.requestList = []
            this.total = 0
            console.error('获取维修申请列表失败:', error)
            this.$message.error('获取维修申请列表失败')
          })
      },
      
      getDeviceList() {
      // 调用API获取设备列表
      deviceApi.list().then(res => {
        // 处理不同的数据返回格式
        let rawData = []
        if (Array.isArray(res)) {
          // 情况1：直接返回数组
          rawData = res
        } else if (res && res.data) {
          // 情况2：返回对象，且有data字段
          if (Array.isArray(res.data)) {
            // 情况2.1：data是数组
            rawData = res.data
          } else if (Array.isArray(res.data.records)) {
            // 情况2.2：data是分页对象，有records数组
            rawData = res.data.records
          }
        }
        // 处理数据映射
        this.deviceList = rawData.map(item => ({
          id: item.id,
          device_name: item.deviceName || item.name || '未命名设备'
        }))
      }).catch(error => {
        this.deviceList = []
        this.$message.error('获取设备列表失败：' + (error.message || '未知错误'))
        console.error('获取设备列表失败:', error)
      })
    },
    handleSearch() {
      // 搜索逻辑
      this.currentPage = 1
      this.getRequestList()
    },
    handleReset() {
      // 重置搜索条件
      this.searchForm = {
        requestCode: '',
        status: '',
        request_time: ''
      }
      this.getRequestList()
    },
    handleAdd() {
      // 新增申请
      this.dialogTitle = '新增维修申请'
      this.form = {
        id: '',
        device_id: '',
        fault_description: '',
        priority: 2, // 默认普通优先级
        estimated_cost: '',
        repair_remarks: ''
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
        // 编辑申请
        if (row.status !== 1) {
          this.$message.warning('只有待指派的申请才能编辑')
          return
        }
        this.dialogTitle = '编辑维修申请'
        // 确保字段名称正确映射
        this.form = {
          id: row.id,
          device_id: row.deviceId || row.device_id,
          fault_description: row.faultDescription || row.fault_description,
          priority: Number(row.priority) || 2, // 确保优先级是数字类型
          estimated_cost: row.estimatedCost || row.estimated_cost || '',
          repair_remarks: row.repairRemarks || row.repair_remarks || ''
        }
        this.dialogVisible = true
      },
    handleDelete(row) {
      // 删除申请
      if (row.status !== 1) {
        this.$message.warning('只有待指派的申请才能删除')
        return
      }
      this.$confirm(`确定要删除申请「${row.request_no || row.id}」吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 执行删除操作
        repairApi.delete(row.id).then(res => {
          this.$message.success('删除成功')
          this.getRequestList()
        }).catch(error => {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
          console.error('删除申请失败:', error)
        })
      }).catch(() => {
        // 取消删除
      })
    },
    handleView(row) {
      // 查看申请详情
      this.$router.push(`/maintenance/request/detail/${row.id}`)
    },
    handleSubmit() {
      // 提交表单
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 准备提交数据，确保字段名正确映射和类型正确
          const submitData = {...this.form}
          
          // 确保数字类型字段正确转换
          submitData.priority = Number(submitData.priority)
          console.log(submitData,"submitData")
          if (submitData.estimated_cost) {
            submitData.estimated_cost = Number(submitData.estimated_cost)
          }
          
          // 确保设备ID存在且正确映射
          if (submitData.device_id) {
            // 添加deviceId字段，确保后端能正确接收设备ID
            submitData.deviceId = submitData.device_id
          }
          
          // 创建时自动设置状态为待指派和申请人ID
          if (!submitData.id) {
            submitData.status = 1
            submitData.requestUserId = this.$store.getters.userId || 1
            submitData.requestTime = new Date()
            submitData.created = new Date()
            // 确保优先级有默认值
            if (!submitData.priority || submitData.priority < 1 || submitData.priority > 3) {
              submitData.priority = 2 // 默认普通优先级
            }
          } else {
            // 更新时设置更新时间
            submitData.updated = new Date()
          }
          
          // 执行相应的操作
          const apiCall = submitData.id ? repairApi.update : repairApi.add
          
          // 创建一个提交对象，同时包含camelCase和snake_case格式的字段，确保fault_description被正确传递
          const faultDescValue = String(submitData.fault_description || '').trim()
          console.log('Fault description being sent:', faultDescValue)
          
          const finalSubmitData = {
            // camelCase format
            deviceId: submitData.device_id || submitData.deviceId,
            faultDescription: faultDescValue,
            estimatedCost: submitData.estimated_cost || submitData.estimatedCost,
            repairRemarks: submitData.repair_remarks || submitData.repairRemarks,
            
            // snake_case format (explicitly adding for the backend)
            device_id: submitData.device_id || submitData.deviceId,
            faultDescValue: faultDescValue,
            estimatedCost: submitData.estimated_cost || submitData.estimatedCost,
            repairRemarks: submitData.repair_remarks || submitData.repairRemarks,
            
            // other fields
            priority: submitData.priority,
            status: submitData.status,
            requestUserId: submitData.requestUserId,
            requestTime: submitData.requestTime,
            created: submitData.created,
            updated: submitData.updated,
            id: submitData.id
          }
          
          
          apiCall(finalSubmitData).then(res => {
            this.$message.success(submitData.id ? '申请更新成功' : '申请提交成功')
            this.dialogVisible = false
            this.getRequestList()
          }).catch(error => {
            this.$message.error((submitData.id ? '更新' : '提交') + '失败：' + (error.message || '未知错误'))
            console.error((submitData.id ? '更新' : '提交') + '申请失败:', error)
          })
        }
      })
    },
    handleCurrentChange(val) {
      // 分页切换
      this.page_num = val
      this.getRequestList()
    },
    handleSizeChange(val) {
      this.page_size = val
      this.getRequestList()
    },
    
    // 获取用户名称
    getUserName(userId) {
      if (!userId || this.userMap[userId]) return
      
      userApi.detail(userId).then(res => {
     
      
        if (res && res.data) {
//           this.userMap[userId] = res.data.username || '未知用户'
//  console.log('this.userMap:', this.userMap[userId])
          this.$set(this.userMap, userId, res.data.username)
         
        }
 
      }).catch(error => {
        console.error('获取用户信息失败:', error)
        this.userMap[userId] = '未知用户'
      })
    },
    
    // 获取设备名称
    getDeviceName(deviceId) {
      if (!deviceId) return '-' 
      const device = this.deviceList.find(item => item.id === deviceId)
      console.log('device:', device)
      return device ? device.device_name : '未知设备' 
    },
    
    // 获取优先级文本
      getPriorityText(priority) {
        return this.priorityText[priority] || '未知'
      },
      
      // 获取状态文本
      getStatusText(status) {
        return this.statusText[status] || '未知状态'
      },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '-' 
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
  }
}
</script>

<style scoped>
.maintenance-request-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>